package com.bt.lms.ui.action.school_education;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import com.bt.lms.constants.BOConstant;
import com.bt.lms.constants.StuStatusBizTypeConstant;
import com.bt.lms.entity.page.Page;

import com.bt.lms.network.msg.ReqMsg;
import com.bt.lms.network.msg.RespMsg;
import com.bt.lms.ui.action.school_education.stu_msg_manage.CheckDetailsAction;
import com.bt.lms.ui.action.school_education.stu_msg_manage.StudentStatusMesAction;

import com.bt.lms.ui.page.school_education.PageStudentList;
import com.bt.lms.ui.vo.school_education.ListConditionSearchInfoVo;
import com.bt.lms.ui.vo.school_education.SEListVo;
import com.bt.lms.ui.vo.user.SchoolEducation;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.scene.Node;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.VBox;
import javafx.util.Callback;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * 分页条件查询事件
 */
public class PagingQueryAction implements EventHandler {

    /**
     * 条件的小盒子
     */
    private VBox vBox;
    /**
     * 大盒子
     */
    public PageStudentList box;

    /**
     * 数据内容
     */
    private TableView<SchoolEducation> dataTV;

    /**
     * 当前页
     */
    private int currentPage = 1;
    /**
     * 每页显示条数
     */
    private int pageCount = 10;

    /**
     * 服务端返回来的总数据
     */
    private long total;

    /**
     * 发送出去的分页条件
     */
    private HashMap<String, Object> input = new HashMap<>();

    /**
     * 分页条件对象
     * @param event the event which occurred
     */
    private final ListConditionSearchInfoVo listConditionSearchInfoVo = new ListConditionSearchInfoVo();

    @Override
    public void handle(Event event) {
        //获取条件
        getInput();

        //数据库查到的所有数据要显示的页数
        int ceil = 0;
        try {
            //按钮
            Button source = (Button) event.getSource();
            String btnStr = source.getText();
            //按钮文本
            if (btnStr.equals("")) {
                return;
            } else if (btnStr.matches("^[0-9]*$")) {
                this.currentPage = Integer.parseInt(btnStr);
                String data = getData(this.currentPage);
                renderData(data);
            } else if (btnStr.equals("GO")) {
                if (!this.box.getTextField().getText().trim().equals("")) {
                    String trim = box.getTextField().getText().trim();
                    int i = 0;
                    //如果输入文本，不通过
                    try {
                         i = Integer.parseInt(trim);
                        ceil = (int) Math.ceil((double) this.total / this.pageCount);
                    }catch (Exception e){
                        Alert alert = new Alert(Alert.AlertType.WARNING);
                        alert.setContentText("您输入的内容有误，请重新输入");
                        alert.showAndWait();
                        return;
                    }
                    this.currentPage = i;
                    String data = getData(this.currentPage);
                    renderData(data);
                }
            } else if (btnStr.equals("搜索")) {
                //获取数据内容
                this.currentPage = 1;
                String data = getData(this.currentPage);
                renderData(data);
            }
        } catch (Exception e) {
            //label
            Label source = (Label) event.getSource();
            String labStr = source.getText();
            if (labStr.equals("<<上一页")) {
                //获取数据内容
                if (this.currentPage == 1) {
                    String data = getData(this.currentPage);
                    renderData(data);
                } else {
                    this.currentPage = this.currentPage - 1;
                    String data = getData(this.currentPage);
                    renderData(data);
                }
            } else if (labStr.equals("下一页>>")) {

                if (this.currentPage == ceil) {
                    return;
                } else {
                    this.currentPage = this.currentPage + 1;
                    String data = getData(this.currentPage);
                    renderData(data);
                }

            } else if (labStr.equals("<<首页")) {
                this.currentPage = 1;
                String data = getData(this.currentPage);
                renderData(data);
            } else if (labStr.equals("尾页>>")) {
                ceil = (int) Math.ceil((double) this.total / this.pageCount);
                this.currentPage = ceil;
                String data = getData(this.currentPage);
                renderData(data);
            }
        }



    }


    /**
     * 获取用户输入
     *
     * @return 条件查询vo
     */
    private void getInput() {
        //条件语句
        ComboBox<String> conditionCB = this.box.getConditionCB();
        String value =  conditionCB.getValue();
        //条件名称
        TextField conditionTF = this.box.getConditionTF();
        int leave = -1;
        switch (value) {
            case "按招生计划":
                leave = BOConstant.STU_STATUS_LIST_ORDER_BYTE_ENP_PLAN;
                String enpStr = conditionTF.getText().trim();
                this.listConditionSearchInfoVo.setPlanName(enpStr);
                break;
            case "按学习中心":
                leave = BOConstant.STU_STATUS_LIST_ORDER_BYTE_LEANING_CENTER;
                String centerStr = conditionTF.getText().trim();
                this.listConditionSearchInfoVo.setPlanName(centerStr);
                break;
            case "按专业":
                leave = BOConstant.STU_STATUS_LIST_ORDER_BYTE_MAJOR;
                String majorStr = conditionTF.getText().trim();
                this.listConditionSearchInfoVo.setPlanName(majorStr);
                break;
        }
        this.listConditionSearchInfoVo.setSortType(leave);

        //学员编号
        TextField codeTF = this.box.getCodeTF();
        String studentNumberTFStr = codeTF.getText().trim();
        this.listConditionSearchInfoVo.setStuNo(studentNumberTFStr);

        //姓名
        TextField nameTF = this.box.getNameTF();
        String nameStr = nameTF.getText().trim();
        this.listConditionSearchInfoVo.setStuName(nameStr);

        ComboBox<String> statusCB = this.box.getStatusCB();
        String value1 = statusCB.getValue();
        int status = -1;
        switch (value1) {
            case "在籍":
                status = BOConstant.STU_STATUS_BASIC_INFO_CURRENT_STATE_Be_REGISTERED;
                break;
            case "未注册":
                status = BOConstant.STU_STATUS_BASIC_INFO_CURRENT_STATE_UNREGISTERED;
                break;
            case "转出":
                status = BOConstant.STU_STATUS_BASIC_INFO_CURRENT_STATE_ROLLOUT;
                break;
            case "休学":
                status = BOConstant.STU_STATUS_BASIC_INFO_CURRENT_STATE_TEMPORARY_ABSENCE_FROM_SCHOOL;
                break;
            case "退学":
                status = BOConstant.STU_STATUS_BASIC_INFO_CURRENT_STATE_DROP_OUT;
                break;
            case "开除":
                status = BOConstant.STU_STATUS_BASIC_INFO_CURRENT_STATE_EXPEL;
                break;
            case "毕业":
                status = BOConstant.STU_STATUS_BASIC_INFO_CURRENT_STATE_GRADUATE;
                break;
            case "异动中":
                status = BOConstant.STU_STATUS_BASIC_INFO_CURRENT_STATE_TRANSACTIONED;
                break;
        }
        this.listConditionSearchInfoVo.setSeState(status);

    }

    /**
     * 获取界面初始数据
     */
    public String getData(int currentPage) {
        String data = null;

        ReqMsg reqMsg = new ReqMsg();
        reqMsg.setBizType((short) 2000);
        reqMsg.setReqId(new Date().getTime());
        Page<Object> page = new Page<>();
        page.setListConditionSearchInfoVo(this.listConditionSearchInfoVo);
        page.setCurrent(currentPage);
        page.setSize(this.pageCount);
        String listStr = JSONObject.toJSONString(page);
        reqMsg.setData(listStr);
        byte[] bytes = reqMsg.toBytes();
        try {
            Socket socket = new Socket("127.0.0.1", 8888);
            OutputStream out = socket.getOutputStream();
            out.write(bytes);

            //接收响应消息
            InputStream in = socket.getInputStream();
            byte[] buf = new byte[4096];
            int read = in.read(buf);
            RespMsg respMsg = RespMsg.toRespMsg(buf);
            data = respMsg.getData();
        } catch (Exception e) {
            Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
            alert.setContentText("网络有点小问题哦，请稍后再试");
            alert.showAndWait();
            return "网络有点小问题哦，请稍后再试";
        }

        return data;
    }


    /**
     * 获取数据内容
     * 根据当前的页数
     *
     * @param data 数据
     */
    public void renderData(String data) {
        Page<SEListVo> parsed = JSONObject.parseObject(data, Page.class);
        parsed.setCurrent(this.currentPage);
        parsed.setSize(this.pageCount);
        List<SEListVo> records = parsed.getRecords();
        List<SchoolEducation> schoolEducations = new ArrayList<>();
        this.total = parsed.getTotal();
        //姓名
        String name = null;
        for (Object o : records) {
            SEListVo s = JSONObject.parseObject(o.toString(), SEListVo.class);
            Long no = s.getNo();
            String stuNo = s.getStuNo();
            name = s.getName();
            String sex = s.getSex();
            String leave = "";
            switch (sex) {
                case "1":
                    leave = "男";
                    break;
                case "2":
                    leave = "女";
                    break;
            }
            String learnCenter = s.getLearnCenter();
            String major = s.getMajor();
            String enp = s.getEnp();
            String phone = s.getPhone();
            SchoolEducation schoolEducation = new SchoolEducation(no, stuNo, name, leave, learnCenter, major, enp, null, phone, "null", "daw ");
            schoolEducation.setTotal(total);
            schoolEducations.add(schoolEducation);
        }

        this.dataTV = new TableView<>();
        double width = 1200;
        //创建列头
        TableColumn<SchoolEducation, Long> numberTab = new TableColumn<>("序号");
        numberTab.setPrefWidth(width / 15);
        TableColumn<SchoolEducation, String> studentTab = new TableColumn<>("学员编号");
        studentTab.setPrefWidth(width / 12);
        TableColumn<SchoolEducation, String> nameTab = new TableColumn<>("姓名");
        nameTab.setPrefWidth(width / 10);
        TableColumn<SchoolEducation, String> sexTab = new TableColumn<>("性别");
        sexTab.setPrefWidth(width / 15);
        TableColumn<SchoolEducation, String> studyTab = new TableColumn<>("学习中心");
        studyTab.setPrefWidth(width / 12);
        TableColumn<SchoolEducation, String> specialtyTab = new TableColumn<>("专业");
        specialtyTab.setPrefWidth(width / 12);
        TableColumn<SchoolEducation, String> enrollPlanTab = new TableColumn<>("招生计划");
        enrollPlanTab.setPrefWidth(width / 8);
        TableColumn<SchoolEducation, String> classroomTab = new TableColumn<>("班级名称");
        classroomTab.setPrefWidth(width / 15);
        TableColumn<SchoolEducation, String> phoneTab = new TableColumn<>("手机号码");
        phoneTab.setPrefWidth(width / 10);
        TableColumn<SchoolEducation, String> stateTab = new TableColumn<>("学籍状态");
        stateTab.setPrefWidth(width / 13);
        TableColumn<SchoolEducation, String> operationTab = new TableColumn<>("操作");
        operationTab.setPrefWidth(width / 8);
        this.dataTV.getColumns().add(numberTab);
        this.dataTV.getColumns().add(studentTab);
        this.dataTV.getColumns().add(nameTab);
        this.dataTV.getColumns().add(sexTab);
        this.dataTV.getColumns().add(studyTab);
        this.dataTV.getColumns().add(specialtyTab);
        this.dataTV.getColumns().add(enrollPlanTab);
        this.dataTV.getColumns().add(classroomTab);
        this.dataTV.getColumns().add(phoneTab);
        this.dataTV.getColumns().add(stateTab);
        this.dataTV.getColumns().add(operationTab);
        //学员状态
        stateTab.setCellFactory(new Callback<TableColumn<SchoolEducation, String>, TableCell<SchoolEducation, String>>() {
            @Override
            public TableCell<SchoolEducation, String> call(TableColumn<SchoolEducation, String> param) {
                return new TableCell<SchoolEducation, String>() {
                    @Override
                    protected void updateItem(String item, boolean empty) {
                        super.updateItem(item, empty);
                        if (item != null) {
                            Label label = new Label("在籍");
                            label.setStyle("-fx-text-fill: #11ff00");
                            setGraphic(label);
                        }
                    }
                };
            }
        });
        //操作学员学籍管理
        operationTab.setCellFactory(new Callback<TableColumn<SchoolEducation, String>, TableCell<SchoolEducation, String>>() {
            @Override
            public TableCell<SchoolEducation, String> call(TableColumn<SchoolEducation, String> param) {
                return new TableCell<SchoolEducation, String>() {
                    @Override
                    protected void updateItem(String item, boolean empty) {
                        super.updateItem(item, empty);
                        if (item != null) {
                            Label number1Lab = new Label("学员学籍信息管理");
                            number1Lab.setPrefHeight(31);
                            number1Lab.setStyle("-fx-text-fill: #00ccff");
                            setGraphic(number1Lab);
                            //给number1Lab设置点击事件
                            StudentStatusMesAction studentStatusMesAction = new StudentStatusMesAction(number1Lab);
                            number1Lab.setOnMouseEntered(studentStatusMesAction);
                        }
                    }
                };
            }
        });

        //姓名
//
        nameTab.setCellFactory(new Callback<TableColumn<SchoolEducation, String>, TableCell<SchoolEducation, String>>() {
            @Override
            public TableCell<SchoolEducation, String> call(TableColumn<SchoolEducation, String> param) {
                return new TableCell<SchoolEducation, String>() {
                    @Override
                    protected void updateItem(String item, boolean empty) {
                        super.updateItem(item, empty);
                        if (item != null) {
                            Label nameLab = new Label(item);
                            nameLab.setStyle("-fx-text-fill: #00ccff");
                            //给名字添加查看详情事件
                            CheckDetailsAction checkDetailsAction = new CheckDetailsAction(nameLab);
                            nameLab.setOnMouseEntered(checkDetailsAction);
                            setGraphic(nameLab);
                        }
                    }
                };
            }
        });

        //配置列映射，让每一列知道要展示的属性是哪一个
        numberTab.setCellValueFactory(new PropertyValueFactory<>("number"));
        studentTab.setCellValueFactory(new PropertyValueFactory<>("studentNumber"));
        nameTab.setCellValueFactory(new PropertyValueFactory<>("name"));
        sexTab.setCellValueFactory(new PropertyValueFactory<>("sex"));
        studyTab.setCellValueFactory(new PropertyValueFactory<>("studyCenter"));
        specialtyTab.setCellValueFactory(new PropertyValueFactory<>("specialty"));
        enrollPlanTab.setCellValueFactory(new PropertyValueFactory<>("enrollPlan"));
        classroomTab.setCellValueFactory(new PropertyValueFactory<>("classroomName"));
        phoneTab.setCellValueFactory(new PropertyValueFactory<>("phone"));
        stateTab.setCellValueFactory(new PropertyValueFactory<>("studentStatusState"));
        operationTab.setCellValueFactory(new PropertyValueFactory<>("operation"));

        //将用户数据集合转换成Javafx组件集合
        ObservableList<SchoolEducation> users = FXCollections.observableArrayList(schoolEducations);
        //把数据放入表格当中
        this.dataTV.setItems(users);
        if (this.box != null) {
            ObservableList<Node> children = this.box.getChildren();
            if (children.size() != 0) {
                children.set(3, this.dataTV);
            }
        }

    }

    public VBox getvBox() {
        return vBox;
    }

    public void setvBox(VBox vBox) {
        this.vBox = vBox;
    }


    public PageStudentList getBox() {
        return box;
    }

    public void setBox(PageStudentList box) {
        this.box = box;
    }

    public int getCurrentPage() {
        return currentPage;
    }

    public void setCurrentPage(int currentPage) {
        this.currentPage = currentPage;
    }

    public int getPageCount() {
        return pageCount;
    }

    public void setPageCount(int pageCount) {
        this.pageCount = pageCount;
    }

    public long getTotal() {
        return total;
    }

    public void setTotal(long total) {
        this.total = total;
    }




    public void setDataTV(TableView<SchoolEducation> dataTV) {
        this.dataTV = dataTV;
    }

    public TableView<SchoolEducation> getDataTV() {
        return dataTV;
    }

    public void setInput(HashMap<String, Object> input) {
        this.input = input;
    }
}
